<template>
	<view class="my-coupons">
		<!-- 标签栏 -->
		<view class="tab-bar">
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'unused' }"
				@click="switchTab('unused')"
			>
				<text class="tab-text">未使用</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'used' }"
				@click="switchTab('used')"
			>
				<text class="tab-text">已使用</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: activeTab === 'expired' }"
				@click="switchTab('expired')"
			>
				<text class="tab-text">已过期</text>
			</view>
		</view>

		<!-- 加载状态 -->
		<view v-if="isLoading" class="loading-state">
			<view class="loading-spinner"></view>
			<text class="loading-text">正在加载优惠券...</text>
		</view>
		

		
		<!-- 优惠券列表 -->
		<view class="coupon-list" v-if="!isLoading">
			<view class="coupon-item" v-for="(coupon, index) in filteredCoupons" :key="index">
				<!-- 左侧橙色区域 -->
				<view class="coupon-left">
					<view class="coupon-name">{{ coupon.couponName || '优惠券' }}</view>
					<view class="consume-threshold">
						{{ coupon.consumeThreshold === '0' || coupon.consumeThreshold === 0 ? '无门槛' : `满${coupon.consumeThreshold}可用` }}
					</view>
				</view>
				
				<!-- 右侧白色区域 -->
				<view class="coupon-right">
					<!-- 新到标签 -->
					<view class="new-tag" v-if="coupon.isNew">新到</view>
					
					<view class="coupon-info">
						<view class="store-name">{{ coupon.storeName || '未知店铺' }}</view>
						<view class="usage-scope">{{ coupon.usageScope }}</view>
						<view class="expire-date">{{ coupon.expireDate }}</view>
					</view>
					
					<view class="use-btn" @click="useCoupon(coupon)">
						<text class="btn-text">{{ getButtonText(coupon.status) }}</text>
					</view>
					
					<!-- 背景水印 -->
					<view class="watermark">优惠券</view>
				</view>
			</view>
		</view>

		<!-- 没有更多数据提示 -->
		<view class="no-more-data">
			<text class="no-more-text">没有更多数据了</text>
		</view>
	</view>
</template>

<script>
	import { get } from '@/config/request'
	
	export default {
		data() {
			return {
				activeTab: 'unused',
				userId: '', // 用户ID
				isLoading: false, // 加载状态
				couponList: [] // 优惠券列表
			}
		},
		onLoad() {
			// 获取用户ID
			this.getUserId();
		},
		
		// 下拉刷新
		onPullDownRefresh() {
			this.fetchUserCoupons().then(() => {
				uni.stopPullDownRefresh();
			});
		},
		computed: {
			filteredCoupons() {
				// 根据activeTab和API返回的status字段过滤优惠券
				return this.couponList.filter(coupon => {
					if (this.activeTab === 'unused') {
						return coupon.status === 0; // status为0表示可用
					} else if (this.activeTab === 'used') {
						return coupon.status === 1; // status为1表示已使用
					} else if (this.activeTab === 'expired') {
						return coupon.status === -1; // status为-1表示不可用/已过期
					}
					return false;
				});
			}
		},
		methods: {
			// 获取用户ID
			getUserId() {
				try {
					// 从缓存中获取用户ID
					const userInfo = uni.getStorageSync('userInfo');
					
					
					if (userInfo && userInfo.id) {
						this.userId = userInfo.id;
						
						// 获取用户优惠券
						this.fetchUserCoupons();
					} else if (userInfo && userInfo.memberId) {
						this.userId = userInfo.memberId;
						
						// 获取用户优惠券
						this.fetchUserCoupons();
					} else {
						// 如果没有用户信息，尝试其他方式获取
						this.getUserIdFromOtherSource();
					}
				} catch (error) {
					console.error('获取用户ID失败:', error);
					uni.showToast({
						title: '获取用户信息失败',
						icon: 'none'
					});
				}
			},
			
			// 从其他来源获取用户ID
			getUserIdFromOtherSource() {
				try {
					// 尝试从其他缓存键获取
					const token = uni.getStorageSync('token');
					const userId = uni.getStorageSync('userId');
					const memberId = uni.getStorageSync('memberId');
			
					if (userId) {
						this.userId = userId;
						this.fetchUserCoupons();
					} else if (memberId) {
						this.userId = memberId;
						this.fetchUserCoupons();
					} else if (token) {
						// 如果有token，可以尝试解析或调用其他接口获取用户ID
						this.userId = '1'; // 临时使用默认值
						this.fetchUserCoupons();
					} else {
	
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('从其他来源获取用户ID失败:', error);
				}
			},
			
			// 获取用户优惠券
			async fetchUserCoupons() {
				if (!this.userId) {
					uni.showToast({
						title: '用户ID不存在',
						icon: 'none'
					});
					return;
				}
				
				console.log('开始获取优惠券，用户ID:', this.userId);
				
				this.isLoading = true;
				uni.showLoading({
					title: '加载中...'
				});
				
				try {
					// 调用API获取用户优惠券
					
					const response = await get(`/promotion1/userjuan/memberUserId/${this.userId}`);
					
				
					
					if (response && response.data) {
						const coupons = response.data;
						
						
						// 先创建基础优惠券数据
						this.couponList = coupons.map(coupon => ({
							id: coupon.id,
							couponId: coupon.couponId, // 保存couponId用于获取详情
							discount: `${coupon.amount || 0}元`,
							minAmount: `满${coupon.condition || 0}可用`,
							usageScope: `使用范围:${coupon.description || '全店商品使用'}`,
							expireDate: coupon.validDate || '2025-12-31 23:59:59',
							status: coupon.status, // 保持API返回的原始status
							isNew: coupon.isNew || false,
							storeName: '', // 店铺名称
							couponName: '', // 优惠券名称
							consumeThreshold: '' // 消费门槛
						}));
					
						
						// 为每个优惠券获取详细信息
						
						await this.fetchCouponDetails();
						
						
					} else {
						console.log('没有优惠券数据，response:', response);
						this.couponList = [];
					}
					
				} catch (error) {
					console.error('获取优惠券失败:', error);
					console.error('错误详情:', {
						message: error.message,
						stack: error.stack,
						userId: this.userId
					});
					
					// 根据错误类型显示不同的提示
					if (error.message && error.message.includes('401')) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
					} else if (error.message && error.message.includes('403')) {
						uni.showToast({
							title: '权限不足',
							icon: 'none'
						});
					} else {
						uni.showToast({
							title: '获取优惠券失败',
							icon: 'none'
						});
					}
					
					// 加载失败时显示空状态
					this.couponList = [];
				} finally {
					this.isLoading = false;
					uni.hideLoading();
				}
			},
			
			// 获取优惠券详细信息
			async fetchCouponDetails() {
				if (!this.couponList || this.couponList.length === 0) {
					return;
				}
				
				
				
				// 创建新的优惠券列表来确保Vue的响应性
				const updatedCouponList = [];
				
				// 为每个优惠券获取详细信息
				for (let i = 0; i < this.couponList.length; i++) {
					const coupon = this.couponList[i];
					
					
					if (coupon.couponId) {
						try {
						
							const detailResponse = await get(`/promotion1/lingJuanZhongXin/coupon/${coupon.couponId}`);
							
							
							
							if (detailResponse && detailResponse.data) {
								// 处理数组响应：如果data是数组，取第一个元素
								const detail = Array.isArray(detailResponse.data) ? detailResponse.data[0] : detailResponse.data;
								
								
								// 创建更新后的优惠券对象
								const updatedCoupon = {
									...coupon,
									storeName: detail.storeName || '未知店铺',
									couponName: detail.couponName || '优惠券',
									consumeThreshold: detail.consumeThreshold || '0'
								};
								
								
								
								updatedCouponList.push(updatedCoupon);
								
							} else {
								
								updatedCouponList.push({
									...coupon,
									storeName: '无详情数据',
									couponName: '优惠券',
									consumeThreshold: '0'
								});
							}
						} catch (error) {
							
							// 设置默认值
							updatedCouponList.push({
								...coupon,
								storeName: '获取失败',
								couponName: '优惠券',
								consumeThreshold: '0'
							});
						}
					} else {
						
						updatedCouponList.push({
							...coupon,
							storeName: '无couponId',
							couponName: '优惠券',
							consumeThreshold: '0'
						});
					}
				}
				
				
				
				// 一次性更新整个列表
				this.couponList = [...updatedCouponList];
				
				
				this.couponList.forEach((coupon, index) => {
				});
				
				// 强制更新视图
				this.$forceUpdate();
				
				// 强制触发计算属性重新计算
				this.$nextTick(() => {
					
					
					this.filteredCoupons.forEach((coupon, index) => {
					
					});
				});
			},
			
			switchTab(tab) {
				this.activeTab = tab;
			},
			
			// 根据状态获取按钮文本
			getButtonText(status) {
				if (status === 0) {
					return '立即使用';
				} else if (status === 1) {
					return '已使用';
				} else if (status === -1) {
					return '已过期';
				}
				return '未知状态';
			},
			
			useCoupon(coupon) {
				// 根据API返回的status判断是否可用
				if (coupon.status === 0) { // status为0表示可用
					uni.switchTab({
						url:"/pages/index/index",
						icon: 'none'
					});
				} else {
					uni.showToast({
						title: '优惠券不可用',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style scoped>
	.my-coupons {
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	/* 加载状态 */
	.loading-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.loading-spinner {
		width: 60rpx;
		height: 60rpx;
		border: 4rpx solid #f3f3f3;
		border-top: 4rpx solid #ff4444;
		border-radius: 50%;
		animation: spin 1s linear infinite;
		margin-bottom: 20rpx;
	}
	
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}
	
	.loading-text {
		font-size: 28rpx;
		color: #999;
	}
	


	/* 标签栏 */
	.tab-bar {
		background-color: #fff;
		display: flex;
		padding: 0 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-item {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 30rpx 0;
		position: relative;
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		transition: color 0.3s;
	}

	.tab-item.active .tab-text {
		color: #ff4444;
	}

	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background-color: #ff4444;
		border-radius: 2rpx;
	}

	/* 优惠券列表 */
	.coupon-list {
		padding: 20rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.coupon-item {
		display: flex;
		background-color: #fff;
		border-radius: 20rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
		position: relative;
	}

	/* 左侧橙色区域 */
	.coupon-left {
		background: linear-gradient(135deg, #FF6B35, #FF8C42);
		padding: 40rpx 30rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		min-width: 200rpx;
		position: relative;
	}

	.coupon-left::after {
		content: '';
		position: absolute;
		right: -10rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 20rpx;
		height: 20rpx;
		background-color: #f5f5f5;
		border-radius: 50%;
		box-shadow: 0 0 0 4rpx #f5f5f5;
	}

	.coupon-name {
		color: #fff;
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		text-align: center;
	}

	.consume-threshold {
		color: #fff;
		font-size: 24rpx;
		opacity: 0.9;
		text-align: center;
	}

	/* 右侧白色区域 */
	.coupon-right {
		flex: 1;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		position: relative;
		background-color: #fff;
	}

	/* 新到标签 */
	.new-tag {
		position: absolute;
		top: 20rpx;
		right: 20rpx;
		background-color: #FFD700;
		color: #fff;
		font-size: 20rpx;
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
		font-weight: bold;
		z-index: 3;
	}

	.coupon-info {
		flex: 1;
		margin-right: 20rpx;
	}

	.store-name {
		font-size: 28rpx;
		color: #ff4444;
		font-weight: bold;
		margin-bottom: 10rpx;
	}

	.usage-scope {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 10rpx;
	}

	.expire-date {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 10rpx;
	}

	.detail-link {
		display: flex;
		align-items: center;
	}

	.detail-text {
		font-size: 24rpx;
		color: #999;
		margin-right: 8rpx;
	}

	.use-btn {
		background-color: #ff4444;
		border-radius: 50rpx;
		padding: 15rpx 30rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0 2rpx 10rpx rgba(255, 68, 68, 0.3);
		position: relative;
		z-index: 2;
	}

	.btn-text {
		color: #fff;
		font-size: 24rpx;
		font-weight: 500;
	}

	/* 背景水印 */
	.watermark {
		position: absolute;
		right: 20rpx;
		top: 50%;
		transform: translateY(-50%);
		font-size: 80rpx;
		color: rgba(0, 0, 0, 0.05);
		font-weight: bold;
		z-index: 1;
		pointer-events: none;
	}

	/* 没有更多数据提示 */
	.no-more-data {
		text-align: center;
		padding: 40rpx 0;
	}

	.no-more-text {
		font-size: 24rpx;
		color: #999;
	}
</style> 